/* function Sub(){//这个方法是将DOM对象里面名字为Sub的都找出来.然后被选中的加入到json传递.用ajax交互
	 
            $.ajax({
                cache: true,
                type: "POST",
                url:"updateUserInfo",
                data:$('#user').serialize(),// 你的formid
                async: false,
                error: function(request) {
                    alert("Connection error");
                },
                success: function(data) {
                    alert("successfull!");
                }
            });
 }*/
 
 //全选 与取消全选
 function checkAll() {
	
     var  checkboxs=document.getElementsByName("pic_check");
     if(document.getElementById("select_a").checked){
     for(var i=0;i<checkboxs.length;i++){
         checkboxs[i].checked=true;

     }
     document.getElementById("state").innerHTML="取消"
     }else{
         for(var i=0;i<checkboxs.length;i++){
             checkboxs[i].checked=false;
         }
     document.getElementById("state").innerHTML="全选"
     }
 }
 //显示全选与否按钮
 function showSelect() {
	 var select_a=document.getElementById("select_a");
	 var state=document.getElementById("state");
	 var del=document.getElementById("del");

	 var editer=$('#editer').val();
	 if(editer=="编辑"){
		 select_a.style.display="block";
		 state.style.display="block";
		 del.style.display="block";
		 $("input[name='pic_check']:checkbox").css({display:"block"});
		 $('#edit').html('取消');
		 $('#editer').val('取消');
	 }
	 if(editer=="取消")
	 {
		 select_a.style.display="none";
		 state.style.display="none";
		 del.style.display="none";
		 $("input[name='pic_check']:checkbox").css({display:"none"});
		 $('#edit').html('编辑');
		 $('#editer').val('编辑');
	 }
	 
	
}
//计算视频数量
 /*$(document).ready(function(){ 
	   var ns= new Array();
     var nums=$('#listNums').val();
      for (var i = 0; i < nums; i++) {
    	  var num1=Math.random()*10; 
          var num2=Math.random()*10;
          var num3=parseInt(num2/10)/10;
          var num4=num1+num3;
          ns.push(num4);
	}
      $('#cn').html(nums);
	 
	 }); */
 $(document).ready(function(){
	 deleSelect();
	 uploadTpic();
	 /* 显示要修改的图片 model */
	 picUpdateModal();
 });
 
 // 删除选中的图片
 function  deleSelect(){
	 $("#del").on("click", function(){//这个方法是将DOM对象里面名字为Sub的都找出来.然后被选中的加入到json传递.用ajax交互
		 	
		 	//获取选中的checkbox集合 删除 js中的图片
		    var ckids =$("input:checkbox[name =pic_check]:checked");
		    //删除数据库中的图片
		    var delstrs = "";
		    for (var i = 0; i < ckids.length; i++) {
				delstrs += $(ckids[i]).parent().parent(".picDel").attr("del_pid"); //parent()只能找上一父级元素
				delstrs += "-";
			}
		    //去掉多余的"-"
		    var delIds = delstrs.substring(0,delstrs.length-1);
		    alert(delIds);
		    $.ajax({
		    	url:"http://localhost:8080/Anime-sky/delPics/"+delIds, //最后面有一个斜杠
		    	type:"DELETE",
		    	success:function(result){
		    		alert("shanchuchenggong!");
		    	}
		    });
		    $.each(ckids,function(){
		    	if(confirm("确定要删除选中的图片么？")){
		    	$(this).parent().remove();
		    	}
		    });
		    
		    
			/*var cids=$("input[name='pic_check']:checkbox");   //切记只能获取name集合
			 var cls=new Array();
			 for (var i = 0; i < cids.length; i++) {
				if(cids[i].checked==true){
					cls.push(cids[i].value);
				}
			}
		   alert(cls);*/
		     /*$.ajax({
		         //cache: true,
		         type: "POST",
		         url:"deleteCollectionVideos",
		         data:{"videoIds":cls},// 你的formid
		         traditional: true,//加上这个就可以传数组
		         async: false,
		         error: function(request) {
		        	   location.replace(location);
		            // alert("Connection error");
		         },
		         success: function(data) {
		             alert("successfull!");
		          
		         }
		     });*/
		});
 }
 //上传信息标题图片到数据库
 function uploadTpic() {
	 //上传图片js
	   $("#tpic_upload").change(function(){     //用于进行图片上传，返回地址
            var f=$("#tpic_upload").val();
            if(f == null || f ==undefined || f == ''){
                return false;
            }
            if(!/\.(?:png|jpg|bmp|gif|PNG|JPG|BMP|GIF)$/.test(f))
            {
                alert("类型必须是图片(.png|jpg|bmp|gif|PNG|JPG|BMP|GIF)");
                $("#tpic_upload").val('');
                return false;
            }
            var formData = new FormData();
/*            $.each($("#pic_upload")[0].files,function(i,file){
          	  formData.append('files', file);
          	  alert("文件属性"+file);
            });*/
            var file= $("#tpic_upload")[0].files[0];
            formData.append("file", file);
            var pic_id = $("#pic_update_btn").attr("pic_id");
           formData.append('id', pic_id);
            $.ajax({
                type: "POST",
                url: "http://localhost:8080/Anime-sky/uploadtImg",
                data: formData,
                cache: false,
                contentType: false,    //不可缺 避免 JQuery 对其操作，从而失去分界符，而使服务器不能正常解析文件
                processData: false,    //不可缺 默认为true。默认情况下，发送的数据将被转换为对象
                dataType:"json",
                success: function(result) {
                    if(result.code== 520){                        
                       $("#a0").children().css({background:"url("+result.extend.tpic.tpicUrl+")","background-size":"120px 120px","background-repeat":"no-repeat" });
                       $("#a0").attr("del_tpid", result.extend.tpic.tpicId);
                    }else{
                        alert("上传失败");
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert("上传失败，请检查网络后重试");
          
                }
            });
     });  
}
 
 /* 显示要修改的图片 model */
  function picUpdateModal(){
	  //1.我们是按钮创建之前就绑定了click,所以绑定不上
	  //解决1)、可以在创建按钮的时候就绑定click
	  //解决2)、绑定.live()
	  //JQury中没有live,使用on进行替代
	  /* $(".edit_btn").click(function(){
		  alert("edit");
	  }); */
	  
	  $(document).on("click", ".pic_btn", function(){	
		  //清除原来的数据
		  $(".picDel").remove();
		  $("#a0").children().css({background:"url(http://localhost:8080/Anime-sky/static/Adhome/img/default.jpg)","background-size":"120px 120px","background-repeat":"no-repeat" });
		//3.把信息的id传递给模态框的更新按钮
			$("#pic_update_btn").attr("pic_id", $(this).attr("pic_id"));
		   var infoId = $("#pic_update_btn").attr("pic_id");  
			//$.get("${APP_PATH}/getPic", { infoId: pic_id } );
			//doFormRequest("${APP_PATH}/getPic","GET",{infoId: pic_id});
		   $.ajax({
			   url:"http://localhost:8080/Anime-sky/getPic/"+infoId, //后面有一个斜杠
			   type:"GET",
			   success:function(result){
				   if(result.code== 520){
					   if(result.extend.tpic != undefined){
					   //显示标题图片
					   $("#a0").children().css({background:"url("+result.extend.tpic.tpicUrl+")","background-size":"120px 120px","background-repeat":"no-repeat" });
					   $("#a0").attr("del_tpid", result.extend.tpic.tpicId);
					   }
					   //显示内容图片
                       var id = $('#bannerImg li:last').attr('id');
                       id = id.substr(1); //取得a后面的数字
                       id = parseInt(id) + 1;
                       $.each(result.extend.cpics, function(index,item) {
                    	   id = id + index;
                    	   var ids=id;
                           rid = 'a'+id; 
                           //拼接删除按钮                                                
                       var a_hidden="<li class='picDel' style= 'float:left; margin-left:6px;'id='"+ rid +"'; del_pid='"+item.picId+"'><div class='thinkcss' style= 'width:120px;height:142px; position:relative; text-align:center;  border:1.2px solid #d0d0d0; background:url("+item.picUrl+"); background-size:120px 120px;background-repeat:no-repeat'>";
                       var dele_html="<div class='thinkcss2' style='width:120px;height:120px; position:absolute; top:0%;left:0%;'><span><i class='fa fa-trash-o' aria-hidden='true'></i></span> <a href='javascript:void(0)' onclick='delespan("+ids+")' class='now'>&nbsp;</a></div>";
                       var a_html="<a href='#' style='position: absolute;bottom: 0px; left:26%;color:#4B125F' onclick='delespan("+ids+")'>内容图片</a> <input style='position: absolute;display:none; right: 0px; bottom:0px;width:16px; height:16px' value='1' type='checkbox'  name='pic_check' lay-skin='primary'>";
                       var li_html="</div></li>";
                       $('#bannerImg').append(a_hidden+dele_html+a_html+li_html); 
                       });
				   }
			   }
		   });
		   
		   
		   //弹出模态框
			$("#picUpdateModal").modal({
				backdrop:"static"
			});
		  
	  });
	  
	  
	//新增并保存更新图片的方法	
		 $("#pic_update_btn").click(function(){

		 });
	  
 }
  //模拟form 发送get或者post请求
  function doFormRequest(url, action, json){
   var form = document.createElement("form");
   form.action = url;
   form.method = action;

   // append input attribute and valus
   for (var key in json)
   {
       if (json.hasOwnProperty(key))
       {
           var val = json[key];
           input = document.createElement("input");
           input.type = "hidden";
           input.name = key;
           input.value = val;

           // append key-value to form
           form.appendChild(input)
       }
   }

   // send post request
   document.body.appendChild(form);
   form.submit();

   // remove form from document
   document.body.removeChild(form);

}
  

